import store from "@/store";
import { Message } from "element-ui";

// 获取url上的参数
export const getQueryString = (name) => {
  const url = window.location.href.substring(window.location.href.indexOf("?"));
  // console.log(url,'url');
  const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  const r = url.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
};

//处理树状渲染公共方法
export function setTreeData(data, code, pcode) {
  // 删除 所有 children,以防止多次调用
  data.forEach(function (item) {
    delete item.children;
  });
  // 将数据存储为 以 code 为 KEY 的 map 索引数据列
  var map = {};
  data.forEach(function (item) {
    map[item[code]] = item;
  });
  //console.log(map);
  var val = [];
  data.forEach(function (item) {
    // 以当前遍历项，的pcode,去map对象中找到索引的code
    var parent = map[item[pcode]];
    // 如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
    if (parent) {
      (parent.children || (parent.children = [])).push(item);
    } else {
      //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
      val.push(item);
    }
  });
  // console.log(val);
  return val;
}

//文字转化
export function setSType(value) {
  switch (value.toLowerCase()) {
    case "string":
      return "字符型C";
    case "int":
      return "整形I";
    case "long":
      return "数值型N";
    case "byte":
      return "备注型M";
    case "float":
      return "浮点型F";
    case "double":
      return "双精度型B";
    case "char":
      return "字符型C";
    case "boolean":
      return "逻辑型L";
    case "stream":
      return "通用型G";
    case "object":
      return "通用型G";
    default:
      return "字符型";
  }
}

/**
 * 获取用户信息
 * @type {function(): {}}
 */
export const getUserInfo = (() => {
  let userInfo = {}; // 缓存用户信息
  return () => {
    if (userInfo && Object.keys(userInfo).length === 0) {
      try {
        userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
      } catch (e) {
        console.warn("用户信息解析失败", e);
      }
    }
    return userInfo;
  };
})();

export const getAccount = () => {
  let account;
  try {
    account = JSON.parse(window.localStorage.getItem("accountToken"));
  } catch (e) {
    console.error("getAccount", e);
  }
  return account;
};

/**
 * 验证是否有权限
 * @param value String 权限
 * @returns {Boolean}
 */
export function checkPermission(value) {
  const permissions = store.state.permissions;
  const result = permissions.filter((item) => {
    if (value.includes(item.name)) {
      return item.value === "1";
    }
    return false;
  });
  return Boolean(result.length);
}

export function dict2Array(dict, isAll, type = String, filter) {
  const arr = isAll ? [{ id: "", name: "全部" }] : [];

  for (const key in dict) {
    if (filter) {
      filter(key, dict[key]) && arr.push({ id: type(key), name: dict[key] });
    } else {
      arr.push({ id: type(key), name: dict[key] });
    }
  }
  return arr;
}

export function dict2options(dict, config = {}) {
  config = Object.assign(
    {
      hasAll: false,
      filter: () => true,
    },
    config
  );
  const options = [];
  for (const key in dict) {
    if (key.indexOf("__") !== 0) {
      const value = dict.__keyConverter ? dict.__keyConverter(key) : key;
      const item = {
        key: value,
        value: value,
        label: dict[key],
      };
      if (config.filter(item)) {
        options.push(item);
      }
    }
  }
  if (config.hasAll) {
    options.unshift({ key: "-1", value: "", label: "全部" });
  }
  return options;
}

export function order(orderArr, arr, key = "id") {
  return orderArr.map((o) => {
    return arr.find((item) => item[key] === o);
  });
}

export function deepObjectMerge(FirstOBJ, SecondOBJ) {
  // 深度合并对象
  for (const key in SecondOBJ) {
    FirstOBJ[key] = FirstOBJ[key] && FirstOBJ[key].toString() === "[object Object]" ? deepObjectMerge(FirstOBJ[key], SecondOBJ[key]) : (FirstOBJ[key] = SecondOBJ[key]);
  }
  return FirstOBJ;
}

export function splitFileName(filename) {
  const fileNameArr = filename.split(".");
  const extensionName = fileNameArr[fileNameArr.length - 1];
  fileNameArr.pop();
  return [fileNameArr.join(""), extensionName];
}

export function isEmpty(val) {
  if (Array.isArray(val)) {
    return val.length === 0;
  }
  if (typeof val === "object") {
    if (val === null) return true;
    return Object.keys(val).length === 0;
  }

  return val === "" || val === undefined || val === null;
}

export function removeEmptyItem(obj) {
  const newObj = {};
  for (const key of Object.keys(obj)) {
    const value = obj[key];
    if (!isEmpty(value)) {
      newObj[key] = value;
    }
  }
  return newObj;
}

export function fileSize(file) {
  return file.size / 1024 / 1024;
}

export function downloadFile(url, filename) {
  const a = document.createElement("a");
  a.href = (window.gdosComplainFastdfsWeb.indexOf("http") != -1 ? window.gdosComplainFastdfsWeb : window.location.protocol + "//" + window.location.host + window.gdosComplainFastdfsWeb) + "/" + url;
  a.download = filename;
  document.body.appendChild(a);
  a.target = "_blank";
  a.click();
  window.URL.revokeObjectURL(url);
  a.parent.remove(a);
}

export function coverItemdetailDataToTree(data, hasAll) {
  const tree = hasAll ? [{ id: "", name: "全部" }] : [];
  tree.push({
    id: data.id,
    name: data.name,
    label: data.name,
    sort: data.sort,
    itemDetailList: data.categoryList,
    children: data.categoryList,
  });
  return tree;
}

const defaultCoverTreeStructOptions = {};
export function coverTreeStruct(data, options = defaultCoverTreeStructOptions) {
  if (!Array.isArray(data)) {
    data = [data];
  }
  const loop = (rows) => {
    // TODO
  };
}

export function getCitiesByArea(areas, areaName) {
  for (const item of areas) {
    if (item.name === areaName) {
      return item.subList;
    }
  }
  return [];
}

export function postPortalsHeight(height, minHeight = 0) {
  const portalsEle = document.getElementById("portals");
  height = height ? height : portalsEle.clientHeight;
  height = height > minHeight ? height : minHeight;
  // debugger
  console.log("portals height：", height);
  window.parent.postMessage({ type: "portals", message: { height } }, "*");
}

export function itemdetail2Tree(result) {
  return [
    {
      id: "",
      name: "全部",
    },
    {
      id: result.id || "1",
      name: result.name,
      sort: result.sort,
      itemDetailList: result.categoryList,
    },
  ];
}

export function itemdetail2GroupOptions(result) {
  return result.categoryList.map((item) => {
    return {
      label: item.name,
      options: item.itemDetailList.map((item) => {
        return {
          ...item,
          value: item.id,
          label: item.name,
        };
      }),
    };
  });
}

export function removeEmptyChildren(list) {
  for (const item of list) {
    if (item.children && item.children.length > 0) {
      removeEmptyChildren(item.children);
    } else {
      delete item.children;
    }
  }
}

export function department2Tree(result, hasAll = true) {
  removeEmptyChildren(result);
  if (hasAll) {
    result.unshift({
      code: "",
      name: "全部",
    });
  }
  return result;
}

export function getCMSUserInfo() {
  let userInfo;
  userInfo = window.sessionStorage.getItem("cmsUserInfo") || window.sessionStorage.getItem("formCmsLoginMsg");
  try {
    userInfo = JSON.parse(userInfo);
  } catch (e) {
    console.log("没有用户信息", e);
  }
  // TEST 模拟userInfo
  // userInfo = {
  //   buttonType: '',
  //   cmsAuthToken: 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMjMiLCJjcmVhdGVkIjoxNjQ4NjI0MzY3OTMyLCJ1c2VyU291cmNlIjoiYWRtaW4iLCJleHAiOjE2NDk0ODgzNjd9.1iB6pvxFnIXv55w3caZK2mKhenYEGIGVDjQrnes5kL3OVec8pse67qHr_5BFvbfrMft7KELxuHmpPCDXrRqLFQ',
  //   cmsUserEmail: '1470515697@qq.com',
  //   detailId: '',
  //   url: '',
  //   userId: 1378,
  //   userName: 'sdsd',
  //   userType: 1
  // }
  //
  // userInfo = {
  //   buttonType: '',
  //   cmsAuthToken: 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI2MTAxMDIxOTgzMDcyMjA2MTMiLCJjcmVhdGVkIjoxNjYzMTQyOTg5MTQ5LCJ1c2VyU291cmNlIjoiYWRtaW4iLCJleHAiOjE2NjQwMDY5ODl9.RxKL6aM3eSJEjuY3_tryj2nO-HHGYMvAUJvPDlNqtuYr2E5IY3t1u6QOO0xvt43N6Tbkglnztjig1tfd51kBaw',
  //   cmsUserEmail: '1368600859@qq.com',
  //   socialCreditNumber: '',
  //   detailId: '',
  //   idNumber: "610102198307220613",
  //   url: '',
  //   userId: 1457,
  //   userName: '赵植',
  //   userType: 1
  // }

  return userInfo || {};
}

export function menus2Tree(list) {
  const tree = [];
  for (const node1 of list) {
    if (node1.levels === 1) {
      node1.children = [];
      for (const node2 of list) {
        if (node1.id === node2.parentId) {
          node1.children.push(node2);
        }
      }
      tree.push(node1);
    }
  }
  return tree;
}

export function calcWorkOrderCountDownStatus(countDown, status) {
  if (status === 10) return 0;
  // 0.正常 1.即将过期 2过期(停止)
  if (countDown <= 0) return 2;
  if (
    // 待受理 小于 1 天
    (status === 0 && countDown < 86400000) ||
    // 待确认 回退中 小于 1 天
    ((status === 2 || status === 1) && countDown < 86400000) ||
    // 调查中 小于 5 天
    (status === 3 && countDown < 432000000) ||
    // 待办结 小于 2 天
    (status === 4 && countDown < 172800000)
  ) {
    return 1;
  }
  return 0;
}

export function debounce(fn, ms) {
  let pending = false;
  const done = () => {
    pending = false;
  };
  return (...row) => {
    if (pending) return;
    pending = true;
    if (ms) {
      setTimeout(done, ms);
    }
    fn.bind(this)(done, ...row);
  };
}

export function generateWorkOrderStatusArr(base, added) {
  const statusArr = base;
  for (const [condition, val] of added) {
    if (condition) {
      statusArr.push(val);
    }
  }

  const all = [];
  for (const item of statusArr) {
    all.push(item.id);
  }

  statusArr.unshift({ id: all.join(","), name: "全部" });
  return statusArr;
}

export function mergeLeft(baseObj, targetObj) {
  const keys = Object.keys(baseObj);
  const newObj = {};
  for (const key of keys) {
    newObj[key] = targetObj[key];
  }
  return newObj;
}

export function deepGetItem(arr, cb) {
  const get = (arr) => {
    for (const item of arr) {
      if (!cb(item)) {
        if (item.children) {
          get(item.children);
        }
      } else {
        data = item;
        break;
      }
    }
  };
  let data = {};
  get(arr);
  // console.log(data, "get(arr)get(arr)");
  return data || {};
}

export function removeEmptyWithTree(tree) {
  const deep = (tree) => {
    for (const item of tree) {
      if (!item) continue;
      item.label = item.name;
      item.value = item.deptCode;
      if (item.children && item.children.length) {
        deep(item.children);
      } else {
        delete item.children;
      }
    }
  };
  return deep(tree);
}

export function flat(arr) {
  const flatArr = [];
  const recursion = (arr) => {
    for (const item of arr) {
      if (item) {
        item.label = item.name;
        item.value = item.deptCode;
        flatArr.push(item);
        if (item.children) {
          recursion(item.children);
        }
      }
    }
  };
  recursion(arr);
  return flatArr;
}

export function blobDataDownload(blob, filename = new Date().getTime()) {
  if (!blob.size) return Message.warning("暂时没有数据");
  const reader = new FileReader();
  reader.readAsDataURL(blob);
  reader.onload = (e) => {
    const a = document.createElement("a");
    a.download = filename;
    a.href = e.target.result;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };
}

function removeArrayItem(array, callback) {
  const newArray = array.filter((item) => callback);
  return newArray;
}

export function findTreeItem(tree, callback, options = { childrenKey: "children" }) {
  for (const item of tree) {
    if (callback(item)) return item;

    if (item[options.childrenKey]) {
      const result = findTreeItem(item[options.childrenKey], callback, options);
      if (result) return result;
    }
  }
  return null;
}

export function forEachTree(tree, callback, options = { childrenKey: "children" }) {
  for (const item of tree) {
    callback(item);

    if (item[options.childrenKey]) {
      findTreeItem(item[options.childrenKey], callback, options);
    }
  }
  return tree;
}
